#include <iostream>
#include <string>
#include <cstring>
#include <memory>
#include <functional>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <arpa/inet.h>
static const std::string serverip = "127.0.0.1";
static const int default_sockfd = -1;
static const int default_retry_time = 1;
static const int default_max_retrynums = 5;
enum class Status // c++11强类型枚举
{
    NEW,        // 新建连接
    CONNECTED,  // 连接成功
    DISCONNECT, // 重连失败
    CLOSE       // 关闭连接
};

enum ExitCode
{
    USAGE_ERR,
    CREATE_SOCK_ERR,
    CONNECT_ERR
};

using Client_t = std::function<void()>;

class TcpConnection
{
public:
    TcpConnection(const std::string &ip, uint16_t port, Client_t func)
        : _sockfd(default_sockfd),
          _serverip(ip),
          _serverport(port),
          _status(Status::NEW),
          _time_retry(default_retry_time),
          _maxConnectNums(default_max_retrynums),
          _func(func)
    {
    }
    void Connection() // 客户端连接server的功能
    {
        _sockfd = socket(AF_INET, SOCK_STREAM, 0);
        if (_sockfd < 0)
        {
            std::cerr << "create sockfd error!" << std::endl;
            exit(ExitCode::CREATE_SOCK_ERR);
        }

        struct sockaddr_in addr;
        memset(&addr, 0, sizeof addr);
        // ip转网络序列
        ::inet_pton(AF_INET, _serverip.c_str(), &addr.sin_addr.s_addr);
        addr.sin_port = htons(_serverport);
        addr.sin_family = AF_INET;
        int n = connect(_sockfd, (struct sockaddr *)&addr, sizeof(addr));
        if (n < 0)
        {
            DisConnection(); // 关闭套接字
            _status = Status::DISCONNECT;
            return;
        }
        _status = Status::CONNECTED;
        return;
    }
    void ReConnection() // 客户端重连的功能
    {
        int cnt = 1;
        while (cnt <= _maxConnectNums && _status == Status::DISCONNECT)
        {
            std::cout << "当前设备已掉线,尝试重连中... [" << cnt++ << "次]" << std::endl;
            Connection();
            sleep(_time_retry); // 每隔_time_retry就重连一次
        }
        if (cnt > _maxConnectNums)
        {
            std::cerr << "重连达到最大次数,客户端已断开连接！" << std::endl;
            _status = Status::CLOSE;
        }
    }
    void DisConnection() // 断开连接
    {
        if (_sockfd > default_sockfd)
        {
            close(_sockfd);
            _sockfd = default_sockfd;
        }
    }
    void Task()
    {
        //未来也可以用回调函数！
        //_func();
        while (true)
        {
            std::string message = "hello word!";
            //std::getline(std::cin, message);
            ssize_t n = send(_sockfd, message.c_str(), message.size(), 0);
            if (n > 0)
            {
                char buf[4096];
                memset(buf, 0, sizeof buf);

                ssize_t n = recv(_sockfd, buf, sizeof buf, 0);
                if (n > 0)
                {
                    buf[n] = 0;
                    std::cout<<"recvm from msg = "<<buf<<std::endl;
                }
                else
                {
                    _status = Status::DISCONNECT;
                    std::cerr << "recv data error,start reconnect!" << std::endl;
                    break;
                }
            }
            else
            {
                _status = Status::DISCONNECT;
                std::cerr << "send data error,start reconnect!" << std::endl;
                break;
            }
            sleep(1);
        }
    }

    Status ConnectionStatus() // 获取客户端连接状态
    {
        return _status;
    }
    ~TcpConnection() {}

private:
    int _sockfd;
    std::string _serverip; // ip
    uint16_t _serverport;  // 端口号
    Status _status;        // 连接状态
    int _time_retry;       // 尝试重连的时间
    int _maxConnectNums;   // 最大的重连次数
    Client_t _func;        // 回调外部传进来的方法
};

class TcpClient
{
public:
    TcpClient(const std::string &ip, uint16_t port, Client_t func)
        : _connection(ip, port, func)
    {
    }
    ~TcpClient() {}
    void Execute()
    {
        while (true)
        {
            switch (_connection.ConnectionStatus())
            {
            case Status::NEW:
                _connection.Connection();
                break;
            case Status::CONNECTED:
                _connection.Task();
                break;
            case Status::DISCONNECT:
                _connection.ReConnection();
                break;
            case Status::CLOSE:
                _connection.DisConnection();
                return;
            default:
                // 啥都不用做
                break;
            }
        }
    }

private:
    TcpConnection _connection;
};
// usage Client port
int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        // Lambda表达式
        ([]()
         { std::cerr << "Usage: ./Client port" << std::endl; })();
        exit(ExitCode::USAGE_ERR);
    }
    uint16_t serverport = std::stoi(argv[1]);
    std::unique_ptr<TcpClient> client = std::make_unique<TcpClient>(serverip, serverport, []()
                                                                    {
            while(true)
            {
                //test
            } });
            
    client->Execute();
    return 0;
}